package base

import (
	"io/ioutil"
	"net/http"

	"github.com/bitly/go-simplejson"
)

type Response struct {
	HTTPResponse *http.Response
	JSON         *simplejson.Json
	Error        *Error
}

func NewResponse(resp *http.Response) (*Response, error) {
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	j, err := simplejson.NewJson(b)
	if err != nil {
		return nil, err
	}

	e := j.Get("error_response")

	return &Response{
		HTTPResponse: resp,
		JSON:         j,
		Error: &Error{
			Code:    e.Get("code").MustInt64(),
			Msg:     e.Get("msg").MustString(),
			SubCode: e.Get("sub_code").MustString(),
			SubMsg:  e.Get("sub_msg").MustString(),
		},
	}, nil
}
